package com.rybbaby.tss.${baseInfo.modulesName}.${baseInfo.entityName?uncapFirst}.service.imp;

<#assign isSet="0"/>
<#list table.columns as column>
<#--上传文件-->
<#if column.ucf??&&isSet=="0">
<#assign isSet="1"/>
import java.lang.reflect.Field;
import org.springframework.beans.factory.annotation.Autowired;
import javax.persistence.Table;
import java.io.Serializable;
import com.rybbaby.tss.platform.sysFileUseLog.service.ISysFileUseLogService;
import com.rybbaby.tss.platform.sysFiles.service.ISysFilesService;
import com.rybbaby.tss.core.utils.StringUtils;
</#if>
<#if column.datasourceSql??&&column.datasourceSql!="">
import java.util.List;
import java.util.Map;
<#break/>
</#if>
</#list>
<#if logicDeleteMaps?? && logicDeleteMaps?size gt 0>
<#list logicDeleteMaps?keys as tab>
<#if tab==table.tableName>
<#if column.ucf??&&isSet=="0">
<#assign isSet="1"/>
import java.io.Serializable;
import org.springframework.beans.factory.annotation.Autowired;
</#if>
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
import javax.persistence.Table;
import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import com.rybbaby.tss.core.bean.PageBean;
<#break>
</#if>
</#list>
</#if>
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.rybbaby.tss.core.web.service.imp.BaseServiceImp;
import com.rybbaby.tss.${baseInfo.modulesName}.${baseInfo.entityName?uncapFirst}.entity.${baseInfo.entityName};
import com.rybbaby.tss.${baseInfo.modulesName}.${baseInfo.entityName?uncapFirst}.service.I${baseInfo.entityName}Service;

/**
 * @description ${baseInfo.businessDescription}数据库操作服务实现
 * 
 * @author ${baseInfo.author}
 * 
 * @createDate ${baseInfo.nowDate}
 */
@Service
@Transactional
public class ${baseInfo.entityName}ServiceImp extends BaseServiceImp<${baseInfo.entityName}>  implements I${baseInfo.entityName}Service {

	<#assign isSet="0"/>
	<#list table.columns as column>
	<#--上传文件-->
	<#if column.ucf??&&isSet=="0">
	<#assign isSet="1"/>
	@Autowired
	private ISysFilesService sysFilesService;
	@Autowired
	private ISysFileUseLogService sysFileUseLogService;
	
	@Override
	public Serializable save(${baseInfo.entityName} entity , String sessionId , String loginUserId , String ... fileRelevances) throws Exception {
		if(entity == null) {
			return null;
		}
		Serializable businessId = save(entity);
		if(businessId != null) {
			if(fileRelevances != null && fileRelevances.length > 0) {
				Table table = ${baseInfo.entityName}.class.getAnnotation(Table.class);
				String businessTableName = table.name();
				for(String fileRelevance : fileRelevances) {
					if(StringUtils.isNotBlank(fileRelevance)) {
						if(!fileRelevance.contains("=>")) {
							continue;
						}
						String [] fileReleVanceInfo = fileRelevance.split("=>");
						String groupName = fileReleVanceInfo[0];
						String fieldName = fileReleVanceInfo[1];
						if(!sysFilesService.useFile(businessTableName , "<#list  table.columns as column><#if column.isPrimaryKey>${column.columnJavaFieldName}</#if></#list>" , businessId , fieldName , groupName , sessionId , loginUserId , null)) {
							throw new Exception("使用文件失败!");
						}
					}
				}
			}
		}
		return businessId;
	}
	
	@Override
	public void updateEntitiy(${baseInfo.entityName} entity , String sessionId , String loginUserId , String delteFileIds, String ... fileRelevances) throws Exception {
		if(entity != null && entity.getId() != null) {
			saveOrUpdate(entity);
			Class<? extends ${baseInfo.entityName}> cls = entity.getClass();
			if(fileRelevances != null && fileRelevances.length > 0) {
				Table table = ${baseInfo.entityName}.class.getAnnotation(Table.class);
				String businessTableName = table.name();
				for(String fileRelevance : fileRelevances) {
					if(StringUtils.isNotBlank(fileRelevance)) {
						if(!fileRelevance.contains("=>")) {
							continue;
						}
						String [] fileReleVanceInfo = fileRelevance.split("=>");
						String groupName = fileReleVanceInfo[0];
						String fieldName = fileReleVanceInfo[1];
						Field declaredField = cls.getDeclaredField(fieldName);
						declaredField.setAccessible(true);
						Object oldValue = declaredField.get(entity);
						if(!sysFilesService.updateUsedFile(businessTableName , "<#list  table.columns as column><#if column.isPrimaryKey>${column.columnJavaFieldName}</#if></#list>" , entity.getId() , fieldName , groupName , sessionId , loginUserId , delteFileIds , oldValue+"")) {
							throw new Exception("使用文件失败!");
						}
					}
				}
			}
		}
	}
	</#if>
	<#if column.datasourceSql??&&column.datasourceSql!="">
	@Override
	public List<Map<String , Object>> ${column.columnJavaFieldName?uncapFirst}Datasource(){
		String sql${column?index} = "${column.datasourceSql}";
		List<Map<String , Object>> ${column.columnJavaFieldName}_datasources = this.findForJdbc(sql${column?index} , null);
		return ${column.columnJavaFieldName}_datasources;
	}
	
	</#if>
	</#list>
	
	<#if logicDeleteMaps?? && logicDeleteMaps?size gt 0>
	<#list logicDeleteMaps?keys as tab>
	<#if tab==table.tableName>
	@Override
	public PageBean pageList(DetachedCriteria dc , int pageNo , int pageSize) {
		dc.add(Restrictions.or(Restrictions.ne("${logicDeleteMaps[tab]}" , true) , Restrictions.isNull("${logicDeleteMaps[tab]}")));
		return super.pageList(dc , pageNo , pageSize);
	}
	
	@Override
	@Transactional
	public boolean batchDelete(Integer [] ids) throws Exception {
		return this.logicDelete(Arrays.asList(ids));
	}
	
	@Override
	@Transactional
	public boolean batchDelete(String [] ids) throws Exception {
		return this.logicDelete(Arrays.asList(ids));
	}
	
	@Override
	@Transactional
	public void batchDelete(Collection<${baseInfo.entityName}> entitys) {
		List<Object> ids = new ArrayList<Object>();
		entitys.parallelStream().forEach(new Consumer<${baseInfo.entityName}>() {
			
			@Override
			public void accept(${baseInfo.entityName} t) {
				ids.add(<#list table.columns as column><#-- 主键--><#if column.isPrimaryKey>t.get${column.columnJavaGetterOrSetterSuffix}()</#if></#list>);
			}
			
		});
		this.logicDelete(ids);
	}
	
	@Override
	@Transactional
	public void delete(${baseInfo.entityName} entity) {
		List<Object> ids = new ArrayList<Object>();
		ids.add(<#list table.columns as column><#-- 主键--><#if column.isPrimaryKey>entity.get${column.columnJavaGetterOrSetterSuffix}()</#if></#list>);
		this.logicDelete(ids);
	}
	
	@Override
	@Transactional
	public void deleteEntityById(Serializable id) {
		List<Object> ids = new ArrayList<Object>();
		ids.add(id);
		this.logicDelete(ids);
	}
	
	@Transactional
	public boolean logicDelete(List<Object> ids) {
		if(ids == null || ids.isEmpty()) {
			return false;
		}
		String deleteIdentifyingField = "${logicDeleteMaps[tab]}";
		String logicDeleteSql = "UPDATE ${table.tableName} SET " + deleteIdentifyingField + " = 1 WHERE <#list table.columns as column><#-- 主键--><#if column.isPrimaryKey>${column.columnName}</#if></#list> IN('" + StringUtils.join(ids , "','") + "')";
		Integer rows = this.executeSql(logicDeleteSql , new Object []{ });
		return rows == ids.size();
	}
	<#break>
	</#if>
	</#list>
	</#if>
}
